#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>

#define NUM 10

void run_child()
{
    for (int i = 0; i < 5; ++i)
    {
        printf("子进程running... pid: %d ppid: %d\n", getpid(), getppid());
        sleep(1);
    }
}

int main()
{
    pid_t id_arr[NUM] = { 0 };
    for (int i = 0; i < NUM; ++i)
    {
        pid_t id = fork();
        if (id == 0)
        {
            run_child();
            exit(0);
        }
        else if (id > 0)
            id_arr[i] = id;
        else
            printf("fork %d error\n", i);
    }
    sleep(8);
    printf("父进程回收进程\n");
    for (int i = 0; i < NUM; ++i)
    {
        int state = 0;
        //wait(&state);
        pid_t ret = waitpid(id_arr[i], &state, 0);
        if (ret == id_arr[i])
            printf("%d号子进程 pid: %d exit code: %d\n", i, ret, state >> 7);
        else
            printf("wait %d error\n", i);
    }
    return 0;
}
